# from fastapi import FastAPI, HTTPException, status
# from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
# from sqlalchemy.exc import SQLAlchemyError
# from sqlalchemy.orm import sessionmaker
#
# app = FastAPI()
#
# # 创建异步引擎和会话工厂
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/db"
# engine = create_async_engine(SQLALCHEMY_DATABASE_URL, pool_size=10, max_overflow=20)
# async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
#
#
# # 定义一个闭包，用于为 API 接口函数增加数据库异常回滚的功能
# def db_rollback_handler(func):
#     async def wrapper(*args, **kwargs):
#         async with async_session() as session:
#             try:
#                 result = await func(*args, db=session, **kwargs)
#                 await session.commit()
#                 return result
#             except SQLAlchemyError as e:
#                 await session.rollback()
#                 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
#
#     return wrapper
#
#
# # 在路由处理函数中使用闭包来增加数据库异常回滚的功能
# @db_rollback_handler
# async def create_item(item: Item, db: AsyncSession):
#     db.add(item)
#     await db.flush()
#     return {"message": "Item created successfully"}